<template>
  <view class="container">
    <view class="input">
      <input v-model="username" placeholder="请输入用户名" />
    </view>
    <view class="input">
      <input v-model="password" type="password" placeholder="请输入密码" />
    </view>
    <view class="btn-primary" @click="handleLogin">登录</view>
    <view style="margin-top:16px;text-align:center;">
      <text @click="goRegister" style="color:#07c160;">没有账号？去注册</text>
    </view>
  </view>
</template>

<script>
import { login } from '../../api/user.js'
import { mapMutations } from 'vuex'
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    ...mapMutations(['setToken', 'setUser']),
    handleLogin() {
      if (!this.username || !this.password) {
        uni.showToast({ title: '请输入用户名和密码', icon: 'none' })
        return
      }

      console.log('开始登录...') // 调试日志
      login({ username: this.username, password: this.password }).then(result => {
        console.log('登录响应:', result) // 调试日志

        // 现在返回的是完整的result对象
        if (result.code === 200 && result.data) {
          const { token, user } = result.data
          console.log('设置token:', token) // 调试日志
          console.log('设置user:', user) // 调试日志

          this.setToken(token)
          this.setUser(user)

          // 验证是否设置成功
          setTimeout(() => {
            const storedToken = uni.getStorageSync('token')
            const storedUser = uni.getStorageSync('user')
            console.log('验证storage - token:', storedToken) // 调试日志
            console.log('验证storage - user:', storedUser) // 调试日志
          }, 100)

          uni.showToast({ title: '登录成功', icon: 'success' })
          uni.switchTab({ url: '/pages/mine/mine' })
        } else {
          console.error('登录失败:', result.message || '未知错误') // 调试日志
          uni.showToast({ title: result.message || '登录失败', icon: 'none' })
        }
      }).catch(err => {
        // 错误已经在 request.js 中处理了
        console.error('登录失败:', err)
      })
    },
    goRegister() {
      uni.navigateTo({ url: '/pages/register/register' })
    }
  }
}
</script>

<style scoped>
.container {
  padding: 40px 24px;
}
</style>
